# Direct outputs eligible for public release

# GLOBAL SETTINGS --------------------------------------------------------------

options(
  scipen = 999,
  digits = 16,
  max.print = .Machine$integer.max,
  show.error.locations = TRUE,
  warn = 1
)

RNGkind("L'Ecuyer-CMRG")
seed <- 818675309L
set.seed(seed) # setting main seed

# PACKAGES ---------------------------------------------------------------------

library(data.table)

# PACKAGE SETTINGS -------------------------------------------------------------

# data.table
setDTthreads(threads = 1)
options(datatable.print.class = TRUE, datatable.print.keys = TRUE)
# so that printing the data.table also shows the variable type on top

# BEGIN FILE -------------------------------------------------------------------

# Just in case something masks 'source()', use extra deliberate base::source().
base::source("~/code/0-utility-functions/table-and-text-utils.R", local = TRUE)

# READ IN OUR DATA -------------------------------------------------------------

# Focus on the aggregate (+1 to +5) estimates (event_time == 99) throughout

db_w2_wages_dt <-
    readRDS(
        "~/estimation-output/unearned_income_effect_estimates_db_w2_wages_by_gender.rds" #nolint
    )
setnames(db_w2_wages_dt, "ref_event_time", "event_time")
db_w2_wages_dt <- db_w2_wages_dt[event_time == 99]

per_adult_total_empl_income_dt <-
    readRDS(
        "~/estimation-output/unearned_income_effect_estimates_per_adult_total_empl_income_by_gender.rds" #nolint
    )
setnames(per_adult_total_empl_income_dt, "ref_event_time", "event_time")
per_adult_total_empl_income_dt <-
    per_adult_total_empl_income_dt[event_time == 99]

# MAKE TABLE -------------------------------------------------------------------

filedir <- "~/paper/tables/table-A.5.tex"
file.create(filedir)

# Start Table A.5
start_latex_table(
    column_structure = "lcccccc",
    file_dir = filedir,
    append = TRUE
)
add_latex_table_rule(rule_type = "toprule", file_dir = filedir, append = TRUE)
add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

heading_text_input1 <-
    " &  &  & \\multicolumn{4}{c}{Sample} "
write_latex_table_row(heading_text_input1, file_dir = filedir, append = TRUE)

add_latex_cmidrule(
    point_start_col = "l",
    point_end_col = "r",
    start_col = 4,
    end_col = 7,
    file_dir = filedir,
    append = TRUE
)

heading_text_input2 <-
    " \\multirow{3}{*}{Group} & \\multirow{3}{*}{Value} & & \\multirow{2}{*}{Full Sample} & & Quartile 1  &  Quartile 4 " #nolint
write_latex_table_row(heading_text_input2, file_dir = filedir, append = TRUE)

heading_text_input3 <-
    "  & & & & & Pre-Win Income  &  Pre-Win Income "
write_latex_table_row(heading_text_input3, file_dir = filedir, append = TRUE)

heading_text_input4 <-
    "  & & & (1) & & (2)  &  (3) "
write_latex_table_row(heading_text_input4, file_dir = filedir, append = TRUE)

heading_text_input1 <- NULL
heading_text_input2 <- NULL
heading_text_input3 <- NULL
heading_text_input4 <- NULL
rm(
    heading_text_input1,
    heading_text_input2,
    heading_text_input3,
    heading_text_input4
)

add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

# Add body of Table A.5
# - introduce convenience functions given a similar structure throughout

TableA5Row1 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            "\\multirow{4}{*}{%s} & Estimate & & %s & & %s & %s",
            text,
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA5Row2 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Standard Error & & (%s) & & (%s) & (%s)",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA5Row3 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Counterfactual Mean & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA5Row4 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Percentage Change & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}


# Winner Wage Earnings
write_latex_table_row(
        "\\emph{Panel A: Winner Wage Earnings} & & & & & & ",
        file_dir = filedir,
        short_row_height = FALSE,
        append = TRUE
    )
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )
TableA5Row1(
    dt = db_w2_wages_dt[gender == "Female Winner"],
    text = "Female Winner",
    scaler = 1
)
TableA5Row2(
    dt = db_w2_wages_dt[gender == "Female Winner"],
    scaler = 1
)
TableA5Row3(
    dt = db_w2_wages_dt[gender == "Female Winner"],
    scaler = 1
)
TableA5Row4(
    dt = db_w2_wages_dt[gender == "Female Winner"],
    scaler = 100000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = FALSE,
        append = TRUE
    )
TableA5Row1(
    dt = db_w2_wages_dt[gender == "Male Winner"],
    text = "Male Winner",
    scaler = 1
)
TableA5Row2(
    dt = db_w2_wages_dt[gender == "Male Winner"],
    scaler = 1
)
TableA5Row3(
    dt = db_w2_wages_dt[gender == "Male Winner"],
    scaler = 1
)
TableA5Row4(
    dt = db_w2_wages_dt[gender == "Male Winner"],
    scaler = 100000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )
add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

# Per-Adult Total Labor Earnings
write_latex_table_row(
        "\\emph{Panel B: Per-Adult Total Labor Earnings} & & & & & & ", #nolint
        file_dir = filedir,
        short_row_height = FALSE,
        append = TRUE
    )
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )
TableA5Row1(
    dt = per_adult_total_empl_income_dt[gender == "Female Winner"],
    text = "Female Winner",
    scaler = 1
)
TableA5Row2(
    dt = per_adult_total_empl_income_dt[gender == "Female Winner"],
    scaler = 1
)
TableA5Row3(
    dt = per_adult_total_empl_income_dt[gender == "Female Winner"],
    scaler = 1
)
TableA5Row4(
    dt = per_adult_total_empl_income_dt[gender == "Female Winner"],
    scaler = 100000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = FALSE,
        append = TRUE
    )
TableA5Row1(
    dt = per_adult_total_empl_income_dt[gender == "Male Winner"],
    text = "Male Winner",
    scaler = 1
)
TableA5Row2(
    dt = per_adult_total_empl_income_dt[gender == "Male Winner"],
    scaler = 1
)
TableA5Row3(
    dt = per_adult_total_empl_income_dt[gender == "Male Winner"],
    scaler = 1
)
TableA5Row4(
    dt = per_adult_total_empl_income_dt[gender == "Male Winner"],
    scaler = 100000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# End Table A.5
add_latex_table_rule(
  rule_type = "bottomrule",
  file_dir = filedir,
  append = TRUE
)
end_latex_table(file_dir = filedir, append = TRUE)
filedir <- NULL
rm(filedir)

# Housekeeping
db_w2_wages_dt <- NULL
per_adult_total_empl_income_dt <- NULL
rm(
    db_w2_wages_dt,
    per_adult_total_empl_income_dt
)